/*
 * InboundMessageCallback.java
 *
 * Created on May 7, 2009, 12:05 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.naga.bulksender.callback;

import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.naga.bulksender.dal.BulkMessageDaoIfc;
import org.smslib.IInboundMessageNotification;
import org.smslib.InboundMessage;
import org.smslib.Message;
import org.smslib.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
 * Callback Processor implemented the logic to support many User's Custom Callback
 * @author Naga Services
 */
public class InboundMessageCallback implements IInboundMessageNotification{
    private Map<String,InboundProcessor> mapProcessor = null;
    private Log log = LogFactory.getLog(InboundMessageCallback.class);
    private BulkMessageDaoIfc msgDao = null;
    private Service srvSms = null;
    
    /** Creates a new instance of InboundMessageCallback */
    public InboundMessageCallback() {
        
    }
    
    public void setMapProcessor(Map<String,InboundProcessor> map){
        this.mapProcessor = map;
    }
    
    public void setMessageDao(BulkMessageDaoIfc dao) {
        msgDao = dao;
    }
    
    public void process(String gateWay, Message.MessageTypes messageTypes, InboundMessage inboundMessage)  {
        try{
            //Save the new Msg Received
            msgDao.store(inboundMessage);
            //Delete the Msg from the Device
            this.srvSms.deleteMessage(inboundMessage);
            //Take the Text and split
            // Search if the first string is in the catalog of processor
            String text = inboundMessage.getText();
            if ( text == null && text.trim().equals("")){
                return;
            }
            String[] token = StringUtils.split(text, " ");
            InboundProcessor processor = this.mapProcessor.get(token[0].toUpperCase());
            if (processor != null ){
                processor.processInboundMessage(gateWay,messageTypes, inboundMessage);
            }
        }catch(Exception ex){
            log.error("Exception in InboundMessageCallback", ex);
        }
    }
    
    public void setServiceProvider(Service svc){
        this.srvSms = svc;
    }
}
